package com.otitan.la.forest.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.otitan.la.forest.system.dto.MenuDTO;
import com.otitan.la.forest.system.entity.MenuEntity;
import com.otitan.la.forest.system.mapper.MenuMapper;
import com.otitan.la.forest.system.mapper.PermissionMapper;
import com.otitan.la.forest.system.service.MenuService;
import com.otitan.la.forest.system.vo.MenuTreeVO;
import com.otitan.webapp.framework.basepro.exception.code.BaseResponseCode;
import com.otitan.webapp.framework.basepro.model.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuEntity> implements MenuService {

    @Resource
    private MenuMapper menuMapper;
    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public DataResult add(MenuEntity menu, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        boolean isSuccess = this.save(menu);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    @Override
    public DataResult batchDelete(List<String> ids) {
        // 根据菜单ID删除按钮
        int count = permissionMapper.deletePermissionByMenuIds(ids);

        boolean isSuccess = this.removeByIds(ids);
        log.debug("\n>>>>>>>>> 【删除菜单表】 <<<<<<<<<\n操作结果：{}，ids：{}\n>>>>>>>>> ---- <<<<<<<<<", isSuccess, ids);
        return DataResult.success();
    }

    @Override
    public DataResult editor(MenuEntity menu, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        boolean isSuccess = this.updateById(menu);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    @Override
    public DataResult findPageData(long page, long size, MenuDTO menu) {
        Page pagePlug = new Page(page, size);
        LambdaQueryWrapper<MenuEntity> queryWrapper = Wrappers.lambdaQuery();
        if(StrUtil.isNotEmpty(menu.getAppCode())){
            queryWrapper.eq(MenuEntity::getAppCode,menu.getAppCode());
        }
        IPage<MenuEntity> iPage = this.page(pagePlug, queryWrapper);
        return DataResult.success(iPage);
    }

    @Override
    public DataResult findOne(String id) {
        return DataResult.success(this.getById(id));
    }

    /**
    * 获取tree型菜单
    * @author Sunke
    * @param applicationId
    * @return com.otitan.webapp.framework.basepro.model.DataResult
    * @exception
    * @date 2020/9/18 0018 11:44
    */
    @Override
    public List<MenuTreeVO> getTreeMenuList(String appCode, String name, String roleId) {
        List<MenuTreeVO> menuTreeList=menuMapper.findAppMenuTree(appCode, name, roleId);
        List<MenuTreeVO> orgTree=formatData(menuTreeList,"0");
        return orgTree;
    }

    @Override
    public List<MenuTreeVO> findUserMenuTree(String userId, String appCode) {
        List<MenuTreeVO> appList = baseMapper.findUserMenuInfo(userId, appCode);
        return formatData(appList, "0");
    }

    @Override
    public List<MenuTreeVO> formatData(List<MenuTreeVO> list, String parentId) {
        if (CollectionUtil.isNotEmpty(list)) {
            List<MenuTreeVO> res = new ArrayList<>();
            list.forEach(item -> {
                if (parentId.equals(item.getParentId())) {
                    res.add(item);
                }
            });
            for (MenuTreeVO re : res) {
                recursive(re, list);
            }
            return res;
        }
        return null;
    }

    /**
     * 递归创建菜单树
     *
     * @param
     * @return void
     * @throws
     * @author jiachangsen
     * @date 2020/07/16 13:24
     */
    private void recursive(MenuTreeVO res, List<MenuTreeVO> menuDtos) {
        boolean flag = true;
        for (MenuTreeVO dto : menuDtos) {
            if (res.getId().equals(dto.getParentId())) {
                recursive(dto, menuDtos);
                res.getChildren().add(dto);
                res.setLeaf(Boolean.FALSE);
                flag = false;
            }
        }
        if (flag) {
            res.setLeaf(Boolean.TRUE);
        }
    }


    /**
     * 递归获取tree型菜单
     * @param menuDTO
     * @param menuDtoList
     */
    private void getMenuTree(MenuTreeVO menuDTO,List<MenuTreeVO> menuDtoList){
            for(MenuTreeVO menu:menuDtoList){
                if(menuDTO.getId().equals(menu.getParentId())){
                    menuDTO.setLeaf(true);
                    getMenuTree(menu,menuDtoList);
                    menuDTO.getChildren().add(menu);
                }
            }
    }



}